package com.wesley.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author:wesley
 */
public class NIOTest {



    /**
     *
     * 读取一个文件， 内容写入 听过channel写入到buffer ， 再从buffer
     * 按照字符读取出来
     *
     * @throws IOException
     */
    public void testReadFile(String filePath) throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile(filePath, "rw");
        FileChannel fileChannel = accessFile.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int byteRead = fileChannel.read(buffer);  //读取内容到buffer
        while (byteRead != -1) {
            System.out.println("Read " + byteRead); //读取多个字节

            //模式切换 ，buffer从写入变成读取
            buffer.flip();
            while (buffer.hasRemaining()){
                //输出buffer，按照一个个的char输出
                System.out.println((char) buffer.get());
            }
            buffer.clear();
            byteRead = fileChannel.read(buffer);
        }
        accessFile.close();
    }


    /**
     *  从文件1获取内容到channel1中 ， 然后传输到channel2中，然后写入到文件2中。
     *  再从文件2输出buffer内容
     *
     * @throws IOException
     */
    public void channel2channel(String fromPath,String toPath) throws IOException {
        RandomAccessFile file1 = new RandomAccessFile(fromPath, "rw");
        FileChannel fileChannel1 = file1.getChannel();

        RandomAccessFile file2 = new RandomAccessFile(toPath, "rw");
        FileChannel fileChannel2 = file2.getChannel();

        int position = 6;

        //也可以用transferTo
        //fileChannel1.transferTo(position, fileChannel1.size(), fileChannel2);
        fileChannel2.transferFrom(fileChannel1, position, fileChannel1.size());

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int read = fileChannel2.read(buffer);
        while (read != -1) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }
            buffer.clear();
            read = fileChannel2.read(buffer);
        }
        file1.close();
        file2.close();
    }


    public static void main(String[] args) throws IOException {
       String filePath1 = "src/test1.txt";
       String filePath2 = "src/test2.txt";

        new NIOTest().testReadFile(filePath1);
//        new NIOTest().channel2channel(filePath1, filePath2);
    }

}
